package com.yc154.springmvc.web;

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DataConvertor implements Converter<String, Date> {
    @Override
    public Date convert(String source) {
        if (source == null || source.isBlank()) {
            return null;
        }
        try{
            // yyyyMMdd
            if(source.matches("\\d{4}-\\d{2}-\\d{2}")) {
                return new SimpleDateFormat("yyyy-MM-dd").parse(source);
            } else if (source.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}")){
                return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(source);
            }
        } catch ( ParseException e){
            e.printStackTrace();
        }
        return null;
    }
}
